package pattern.platform.aliyun;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pattern.platform.SendSmsBase;
import pattern.sms.SendSmsModel;

import java.util.Objects;

/**
 * 阿里短信发送处理类
 * @author Simon
 **/
@Component("aliSmsHandler")
@Slf4j
public class AliSmsHandler implements SendSmsBase {
    @Autowired
    private AliyunSmsConfig aliyunSmsConfig;

    /**
     * 初始化
     */
    public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(aliyunSmsConfig.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(aliyunSmsConfig.getAccessKeySecret());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信
     */
    @Override
    public Boolean send(SendSmsModel sendSmsModel) {
        Boolean flag = Boolean.FALSE;
        try {
            var client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(sendSmsModel.getPhoneNumbers());
            var templateCode = AliTemplateCode.getCode(sendSmsModel.getTemplateCode());
            if (Objects.isNull(templateCode)) {
                log.error("阿里云未配置短信模板{}", sendSmsModel.getTemplateCode());
                return false;
            }
            sendSmsRequest.setSignName(templateCode.getSign());
            sendSmsRequest.setTemplateCode(templateCode.getCode());
            sendSmsRequest.setTemplateParam(JSON.toJSONString(sendSmsModel.getTemplateParam()));
            sendSmsRequest.setOutId(sendSmsModel.getExtendCode());
            // 复制代码运行请自行打印 API 的返回值
            var sendSmsResponse = client.sendSms(sendSmsRequest);
            if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                log.info("发送短信成功，阿里云平台{}", JSON.toJSONString(sendSmsRequest));
                log.info("发送短信成功，阿里云平台{}", JSON.toJSONString(sendSmsResponse.getBody()));
                flag = true;
            } else {
                log.error("发送短信失败，阿里云平台{}", JSON.toJSONString(sendSmsResponse.getBody()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送短信失败，阿里云平台调用异常");
        }
        return flag;
    }

}
